package com.wzb.mybatisplus.bitaction.electrumaction.five;

import org.bitcoinj.core.*;
import org.bitcoinj.params.MainNetParams;
import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class MinimalParallelKeyFinder {

    private static final NetworkParameters params = MainNetParams.get();
    private static final AtomicLong globalCounter = new AtomicLong(1L);
    private static final AtomicInteger foundCount = new AtomicInteger(0);

    public static void main(String[] args) throws InterruptedException {
        int threadCount = Runtime.getRuntime().availableProcessors();
        int targetCount = 10; // 目标找到的数量
        long maxSearch = Long.MAX_VALUE; // 最大搜索范围

        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(threadCount);

        // 启动工作线程
        for (int i = 0; i < threadCount; i++) {
            executor.execute(new SilentWorker(targetCount, maxSearch));
        }

        // 等待任务完成
        executor.shutdown();
        executor.awaitTermination(24, TimeUnit.HOURS);
    }

    /**
     * 静默工作线程 - 只输出找到的私钥和地址
     */
    static class SilentWorker implements Runnable {
        private final int targetCount;
        private final long maxSearch;

        public SilentWorker(int targetCount, long maxSearch) {
            this.targetCount = targetCount;
            this.maxSearch = maxSearch;
        }

        @Override
        public void run() {
            while (foundCount.get() < targetCount && globalCounter.get() <= maxSearch) {
                long current = globalCounter.getAndIncrement();

                if (current > maxSearch) {
                    break;
                }

                try {
                    ECKey key = ECKey.fromPrivate(BigInteger.valueOf(current));
                    String privateKeyWIF = key.getPrivateKeyAsWiF(params);

                    if (privateKeyWIF.startsWith("5")) {
                        int currentFound = foundCount.incrementAndGet();
                        if (currentFound <= targetCount) {
                            Address address = LegacyAddress.fromKey(params, key);
                            // 只打印私钥和地址
                            System.out.println(privateKeyWIF + " -> " + address);
                        }
                    }

                } catch (Exception e) {
                    // 忽略异常，继续下一个
                }
            }
        }
    }
}
